package cn.hdu.liang.ch02.classpath;

import java.io.BufferedInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;

/**
 * ZIP或JAR文件形式的类路径,起名为ZipJarEntry;
 */
public class ZipJarEntry extends Entry {
    //绝对路径 "/path/to/test.zip"
    String absPath;
    //压缩包名 "test"
    String zipName;

    public ZipJarEntry(String path) {
        File dir = new File(path);
        if(dir.exists()) {
            absPath = dir.getParentFile().getAbsolutePath();
            zipName = dir.getName();
            //去掉结尾的.zip或者.jar
            if(zipName.contains(".")) {
                zipName = zipName.substring(0, zipName.lastIndexOf('.'));
            }
        }
    }

    public ZipJarEntry(String path, String zipName) {
        File dir = new File(path, zipName);
        if(dir.exists()) {
            absPath = dir.getAbsolutePath();
            //去掉结尾的.zip或者.jar
            if(zipName.contains(".")) {
                this.zipName = zipName.substring(0, zipName.lastIndexOf('.'));
            }
        }
    }

    @Override
    public byte[] readClass(String className) throws IOException {
        File file = new File(absPath);

        try(ZipFile zf = new ZipFile(file)) {
            //如果是zip文件,用zipName+"/"+className获取ZipEntry
            //ZipEntry ze = zf.getEntry(zipName + "/" + className);

            //如果是jar包,用className获取ZipEntry
            ZipEntry ze = zf.getEntry(className);
            if(ze == null) {
                return null;
            }

            BufferedInputStream in = new BufferedInputStream(zf.getInputStream(ze));
            ByteArrayOutputStream out = new ByteArrayOutputStream(1024);
            int size = 0;
            byte[] temp = new byte[1024];
            while((size = in.read(temp)) != -1) {
                out.write(temp, 0, size);
            }

            return out.toByteArray();
        }
    }

    @Override
    public String className() {
        return absPath;
    }
}
